use model_graph_types::modeling::{ClassAttribute, ValueSize, ValueType};

pub fn attribute_sql(attribute: &ClassAttribute) -> anyhow::Result<String> {
    //名称
    let column_name = attribute.name.clone();
    //字段类型
    let column_type = get_sqlite_type(&attribute.data_type, &attribute.value_size)?;
    //默认值
    let mut default_value = attribute
        .default_value
        .as_ref()
        .map_or(String::from(""), |f| f.clone());
    //注释

    if attribute.is_autoincrement {
        default_value = String::from("PRIMARY KEY AUTOINCREMENT");
    } else {
        default_value = format!("DEFAULT '{}'", default_value)
    }

    let sql = format!("`{}` {}  {}", column_name, column_type, default_value);

    tracing::debug!("sql:{}", sql);
    Ok(sql)
}

pub fn get_sqlite_type(data_type: &ValueType, size: &ValueSize) -> anyhow::Result<String> {
    //
    match data_type {
        ValueType::String => {
            //
            match size {
                ValueSize::Tiny => Ok(String::from("TEXT")),
                _ => Ok(String::from("TEXT")),
            }
        }
        ValueType::Boolean => Ok(String::from("INTEGER")),
        ValueType::Date => Ok(String::from("INTEGER")),
        ValueType::Timestamp => Ok(String::from("TIMESTAMP")),
        ValueType::Number => Ok(String::from("INTEGER")),
        _ => {
            tracing::error!("获取SQLite列类型失败:{:?}", data_type);
            Err(anyhow::anyhow!("获取SQLite列类型失败:{:?}", data_type))
        }
    }
}
